<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>画圆大师 - 挑战你的圆形绘制能力</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#F59E0B',
                        danger: '#EF4444',
                        dark: '#1E293B',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .glass-effect {
                backdrop-filter: blur(8px);
                background-color: rgba(255, 255, 255, 0.7);
            }
            .drawing-shadow {
                box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
            }
            .btn-bounce {
                transition: transform 0.2s ease;
            }
            .btn-bounce:active {
                transform: scale(0.95);
            }
            .pulse-animation {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.05); }
                100% { transform: scale(1); }
            }
            .float-animation {
                animation: float 3s ease-in-out infinite;
            }
            @keyframes float {
                0% { transform: translateY(0px); }
                50% { transform: translateY(-10px); }
                100% { transform: translateY(0px); }
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen font-sans text-dark">
    <!-- 顶部装饰 -->
    <div class="absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-primary/10 to-transparent -z-10"></div>
    
    <!-- 游戏容器 -->
    <div class="container mx-auto px-4 py-8 max-w-md">
        <!-- 游戏标题 -->
        <div class="text-center mb-8 mt-4">
            <div class="inline-block mb-3">
                <i class="fa fa-circle-o text-primary text-4xl float-animation"></i>
            </div>
            <h1 class="text-[clamp(1.8rem,6vw,2.8rem)] font-bold text-dark mb-2 tracking-tight">画圆大师</h1>
            <p class="text-gray-600 text-sm md:text-base max-w-xs mx-auto">用手指画一个完美的圆，看看你能得多少分！</p>
        </div>
        
        <!-- 游戏区域 -->
        <div class="relative bg-white rounded-3xl p-3 mb-8 drawing-shadow overflow-hidden transition-all duration-300 hover:shadow-lg">
            <!-- 装饰元素 -->
            <div class="absolute -top-10 -right-10 w-20 h-20 bg-primary/5 rounded-full"></div>
            <div class="absolute -bottom-8 -left-8 w-16 h-16 bg-secondary/5 rounded-full"></div>
            
            <!-- 提示圆圈（半透明） -->
            <div id="guideCircle" class="absolute left-1/2 top-1/2 w-[60%] h-[60%] rounded-full border-2 border-primary/20 -translate-x-1/2 -translate-y-1/2 pointer-events-none"></div>
            
            <!-- 画布 -->
            <canvas id="drawingCanvas" class="w-full h-[50vh] rounded-2xl bg-gradient-to-br from-gray-50 to-gray-100"></canvas>
            
            <!-- 状态提示 -->
            <div id="statusText" class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-center glass-effect text-primary px-6 py-3 rounded-full shadow-md opacity-0 transition-all duration-300 transform scale-90">
                <p class="font-medium">开始画圆吧！</p>
            </div>
        </div>
        
        <!-- 控制区域 -->
        <div class="flex flex-col gap-4 mb-8">
            <button id="startBtn" class="bg-primary hover:bg-primary/90 text-white py-4 px-6 rounded-xl font-medium text-lg shadow-lg btn-bounce flex items-center justify-center gap-2 pulse-animation">
                <i class="fa fa-play"></i>
                <span>开始挑战</span>
            </button>
            
            <button id="resetBtn" class="bg-gray-200 hover:bg-gray-300 text-dark py-3 px-6 rounded-xl font-medium shadow-md btn-bounce hidden">
                再玩一次
            </button>
<!--            -->
<!--            <button id="forceScoreBtn" class="bg-accent/80 hover:bg-accent text-white py-2 px-4 rounded-xl font-medium text-sm shadow-md btn-bounce hidden">-->
<!--                强制评分-->
<!--            </button>-->
        </div>
        
        <!-- 游戏说明 -->
        <div class="text-center text-gray-500 text-sm bg-white/50 backdrop-blur-sm p-4 rounded-xl">
            <p class="flex items-center justify-center gap-2">
                <i class="fa fa-lightbulb-o text-accent"></i>
                尽量画一个闭合的圆形，越接近标准圆得分越高
            </p>
        </div>
    </div>
    
    <!-- 评分弹窗 (初始隐藏) -->
    <div id="scoreModal" class="fixed inset-0 flex items-center justify-center z-50 bg-dark/50 backdrop-blur-sm opacity-0 pointer-events-none transition-opacity duration-300">
        <div class="bg-white rounded-3xl p-8 max-w-xs w-full mx-4 transform scale-90 transition-transform duration-300 shadow-2xl">
            <div class="text-center">
                <!-- 评分图标 -->
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 mb-4">
                    <i id="scoreIcon" class="fa fa-meh-o text-3xl text-primary"></i>
                </div>
                
                <!-- 分数显示 -->
                <div class="mb-4">
                    <p class="text-gray-500 mb-1 text-sm">你的得分</p>
                    <p id="scoreDisplay" class="text-[clamp(3rem,15vw,5rem)] font-bold text-primary">0</p>
                </div>
                
                <!-- 反馈文本 -->
                <p id="feedbackText" class="text-gray-600 mb-6 min-h-[40px]"></p>
                
                <!-- 参考圆预览 -->
                <div class="w-32 h-32 mx-auto mb-6 rounded-full border-2 border-dashed border-gray-200 relative overflow-hidden">
                    <canvas id="previewCanvas" class="w-full h-full"></canvas>
                </div>
                
                <!-- 按钮 -->
                <button id="modalCloseBtn" class="w-full bg-primary hover:bg-primary/90 text-white py-3 px-6 rounded-xl font-medium shadow-md btn-bounce">
                    再玩一次
                </button>
            </div>
        </div>
    </div>

    <script>
        // 获取DOM元素
        const canvas = document.getElementById('drawingCanvas');
        const ctx = canvas.getContext('2d');
        const previewCanvas = document.getElementById('previewCanvas');
        const previewCtx = previewCanvas.getContext('2d');
        const startBtn = document.getElementById('startBtn');
        const resetBtn = document.getElementById('resetBtn');
        const forceScoreBtn = document.getElementById('forceScoreBtn');
        const scoreModal = document.getElementById('scoreModal');
        const scoreDisplay = document.getElementById('scoreDisplay');
        const feedbackText = document.getElementById('feedbackText');
        const scoreIcon = document.getElementById('scoreIcon');
        const modalCloseBtn = document.getElementById('modalCloseBtn');
        const statusText = document.getElementById('statusText');
        
        // 设置Canvas尺寸
        function resizeCanvas() {
            // 主画布尺寸
            const { width, height } = canvas.getBoundingClientRect();
            if (canvas.width !== width || canvas.height !== height) {
                canvas.width = width;
                canvas.height = height;
            }
            
            // 预览画布尺寸
            const { width: previewWidth, height: previewHeight } = previewCanvas.getBoundingClientRect();
            if (previewCanvas.width !== previewWidth || previewCanvas.height !== previewHeight) {
                previewCanvas.width = previewWidth;
                previewCanvas.height = previewHeight;
            }
        }
        
        // 初始化时调整一次尺寸
        resizeCanvas();
        // 窗口大小变化时重新调整
        window.addEventListener('resize', resizeCanvas);
        
        // 游戏状态变量
        let isDrawing = false;
        let isGameActive = false;
        let points = [];
        let centerX, centerY, radius;
        let scoreCalculated = false; // 标记是否已计算分数
        
        // 显示状态文本
        function showStatus(text, duration = 2000) {
            statusText.innerHTML = `<p class="font-medium">${text}</p>`;
            statusText.classList.remove('opacity-0', 'scale-90');
            statusText.classList.add('opacity-100', 'scale-100');
            
            if (duration > 0) {
                setTimeout(() => {
                    statusText.classList.remove('opacity-100', 'scale-100');
                    statusText.classList.add('opacity-0', 'scale-90');
                }, duration);
            }
        }
        
        // 开始游戏
        function startGame() {
            // 重置画布
            clearCanvas();
            points = [];
            scoreCalculated = false; // 重置分数计算状态
            
            // 更新UI状态
            isGameActive = true;
            startBtn.classList.add('hidden');
            resetBtn.classList.remove('hidden');
            forceScoreBtn.classList.remove('hidden');
            
            // 显示提示
            showStatus('请用手指画一个圆');
        }
        
        // 重置游戏
        function resetGame() {
            clearCanvas();
            points = [];
            scoreCalculated = false; // 重置分数计算状态
            hideScoreModal();
            showStatus('请再画一个圆');
        }
        
        // 清除画布
        function clearCanvas() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
        
        // 开始绘制
        function startDrawing(x, y) {
            if (!isGameActive || scoreCalculated) return; // 如果已计算分数，不允许再绘制
            
            isDrawing = true;
            points = []; // 重置点数组
            points.push({ x, y });
            
            // 记录初始点
            ctx.beginPath();
            ctx.arc(x, y, 2, 0, Math.PI * 2);
            ctx.fillStyle = '#3B82F6';
            ctx.fill();
        }
        
        // 绘制中
        function draw(x, y) {
            if (!isDrawing || !isGameActive || scoreCalculated) return; // 如果已计算分数，停止绘制
            
            // 记录点
            points.push({ x, y });
            
            // 绘制线条
            ctx.lineWidth = 3;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.strokeStyle = '#3B82F6';
            
            ctx.lineTo(x, y);
            ctx.stroke();
        }
        
        // 结束绘制
        function endDrawing() {
            if (!isDrawing || !isGameActive || scoreCalculated) return; // 如果已计算分数，忽略
            
            isDrawing = false;
            
            // 检查绘制是否足够完整
            if (isDrawingComplete()) {
                scoreCalculated = true; // 标记为已计算分数，防止重复计算
                calculateScore();
            } else {
                // 绘制不完整，但仍然提供评分选项
                showStatus('画的圆不够完整', 3000);
                forceScoreBtn.classList.remove('hidden');
            }
        }
        
        // 强制计算分数
        function forceCalculateScore() {
            if (points.length < 5) {
                showStatus('请先画一个圆', 2000);
                return;
            }
            
            scoreCalculated = true;
            forceScoreBtn.classList.add('hidden');
            calculateScore();
        }
        
        // 检查绘制是否完整
        function isDrawingComplete() {
            // 至少需要15个点才能构成一个圆
            if (points.length < 15) return false;
            
            // 计算中心点（提前计算，用于角度计算）
            calculateCircleParameters();
            
            // 计算所有点相对于中心点的角度
            const angles = points.map(point => {
                return Math.atan2(point.y - centerY, point.x - centerX);
            });
            
            // 对角度进行标准化处理（-π 到 π 之间）
            const normalizedAngles = angles.map(angle => {
                return angle < 0 ? angle + 2 * Math.PI : angle;
            });
            
            // 排序角度以便检查覆盖范围
            normalizedAngles.sort((a, b) => a - b);
            
            // 检查角度覆盖范围（考虑环形特性）
            let maxGap = 0;
            for (let i = 0; i < normalizedAngles.length - 1; i++) {
                const gap = normalizedAngles[i + 1] - normalizedAngles[i];
                maxGap = Math.max(maxGap, gap);
            }
            
            // 检查最后一个到第一个的间隙（环形）
            const wrapGap = (normalizedAngles[0] + 2 * Math.PI) - normalizedAngles[normalizedAngles.length - 1];
            maxGap = Math.max(maxGap, wrapGap);
            
            // 如果最大间隙小于120度（约2.09弧度），认为绘制足够完整
            return maxGap < 2.09; // 2.09 radians ≈ 120 degrees
        }
        
        // 计算圆的中心和半径
        function calculateCircleParameters() {
            // 计算所有点的平均值作为中心
            let sumX = 0, sumY = 0;
            points.forEach(point => {
                sumX += point.x;
                sumY += point.y;
            });
            
            centerX = sumX / points.length;
            centerY = sumY / points.length;
            
            // 计算平均距离作为半径
            let sumDistances = 0;
            points.forEach(point => {
                const dx = point.x - centerX;
                const dy = point.y - centerY;
                sumDistances += Math.sqrt(dx * dx + dy * dy);
            });
            
            radius = sumDistances / points.length;
        }
        
        // 计算分数
        function calculateScore() {
            // 计算圆的参数
            calculateCircleParameters();
            
            // 如果半径太小，视为无效
            if (radius < 20) {
                showStatus('画的圆太小了，请再试一次', 3000);
                // 2秒后允许重新绘制
                setTimeout(() => {
                    scoreCalculated = false;
                    clearCanvas();
                    points = [];
                    forceScoreBtn.classList.remove('hidden');
                }, 2000);
                return;
            }
            
            // 计算每个点到中心的距离与平均半径的偏差
            let totalDeviation = 0;
            points.forEach(point => {
                const dx = point.x - centerX;
                const dy = point.y - centerY;
                const distance = Math.sqrt(dx * dx + dy * dy);
                // 计算相对偏差
                totalDeviation += Math.abs(distance - radius) / radius;
            });
            
            // 计算平均偏差
            const avgDeviation = totalDeviation / points.length;
            
            // 根据平均偏差计算分数 (0-100)
            // 偏差越小，分数越高
            let score = Math.max(0, 100 - avgDeviation * 100 * 5);
            score = Math.round(score);
            
            // 额外考虑圆的闭合程度
            const firstPoint = points[0];
            const lastPoint = points[points.length - 1];
            const endDistance = Math.sqrt(
                Math.pow(lastPoint.x - firstPoint.x, 2) + 
                Math.pow(lastPoint.y - firstPoint.y, 2)
            );
            
            // 闭合程度评分 (0-20分)
            const closureScore = Math.max(0, 20 - endDistance / radius * 20);
            
            // 综合评分 (最高100)
            score = Math.min(100, Math.round(score + closureScore));
            
            // 显示参考圆
            drawReferenceCircle();
            
            // 在预览画布上绘制结果
            drawPreview(score);
            
            // 显示结果弹窗
            showScoreModal(score);
        }
        
        // 绘制参考圆
        function drawReferenceCircle() {
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
            ctx.strokeStyle = 'rgba(16, 185, 129, 0.7)';
            ctx.lineWidth = 2;
            ctx.setLineDash([5, 3]);
            ctx.stroke();
            ctx.setLineDash([]); // 重置虚线
        }
        
        // 在预览画布上绘制用户的圆和参考圆
        function drawPreview(score) {
            // 清除预览画布
            previewCtx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
            
            const previewCenterX = previewCanvas.width / 2;
            const previewCenterY = previewCanvas.height / 2;
            const previewRadius = Math.min(previewCanvas.width, previewCanvas.height) * 0.4;
            
            // 绘制参考圆
            previewCtx.beginPath();
            previewCtx.arc(previewCenterX, previewCenterY, previewRadius, 0, Math.PI * 2);
            previewCtx.strokeStyle = 'rgba(16, 185, 129, 0.5)';
            previewCtx.lineWidth = 2;
            previewCtx.setLineDash([3, 2]);
            previewCtx.stroke();
            previewCtx.setLineDash([]);
            
            // 如果没有点，直接返回
            if (points.length === 0) return;
            
            // 计算缩放和偏移，将用户绘制的圆适配到预览画布
            const userCenterX = centerX;
            const userCenterY = centerY;
            const scale = previewRadius / radius;
            
            // 绘制用户的圆
            previewCtx.beginPath();
            points.forEach((point, index) => {
                // 转换坐标到预览画布
                const x = previewCenterX + (point.x - userCenterX) * scale;
                const y = previewCenterY + (point.y - userCenterY) * scale;
                
                if (index === 0) {
                    previewCtx.moveTo(x, y);
                } else {
                    previewCtx.lineTo(x, y);
                }
            });
            
            // 根据分数设置颜色
            let strokeColor = '#EF4444'; // 低分红色
            if (score >= 60) strokeColor = '#F59E0B'; // 中等分数黄色
            if (score >= 80) strokeColor = '#10B981'; // 高分绿色
            
            previewCtx.strokeStyle = strokeColor;
            previewCtx.lineWidth = 2;
            previewCtx.stroke();
        }
        
        // 显示评分弹窗
        function showScoreModal(score) {
            // 更新分数显示
            scoreDisplay.textContent = 0; // 先重置为0，为动画做准备
            
            // 根据分数给出反馈和图标
            let feedback = '';
            let icon = 'fa-meh-o';
            let iconColor = 'text-accent';
            
            if (score >= 90) {
                feedback = '太棒了！你是画圆大师！';
                icon = 'fa-trophy';
                iconColor = 'text-yellow-500';
            } else if (score >= 70) {
                feedback = '非常好！这是一个很标准的圆。';
                icon = 'fa-smile-o';
                iconColor = 'text-secondary';
            } else if (score >= 50) {
                feedback = '不错！再努力一点就更圆了。';
                icon = 'fa-smile-o';
                iconColor = 'text-primary';
            } else if (score >= 30) {
                feedback = '还可以，继续练习能画得更圆。';
                icon = 'fa-meh-o';
                iconColor = 'text-accent';
            } else {
                feedback = '继续努力，画得更圆一些！';
                icon = 'fa-frown-o';
                iconColor = 'text-danger';
            }
            
            feedbackText.textContent = feedback;
            scoreIcon.className = `fa ${icon} text-3xl ${iconColor}`;
            
            // 显示弹窗
            scoreModal.classList.remove('opacity-0', 'pointer-events-none');
            scoreModal.classList.add('opacity-100', 'pointer-events-auto');
            
            // 弹窗动画
            const modalContent = scoreModal.querySelector('div');
            modalContent.classList.remove('scale-90');
            modalContent.classList.add('scale-100');
            
            // 添加分数动画
            setTimeout(() => {
                animateScore(0, score);
            }, 300);
        }
        
        // 隐藏评分弹窗
        function hideScoreModal() {
            scoreModal.classList.remove('opacity-100', 'pointer-events-auto');
            scoreModal.classList.add('opacity-0', 'pointer-events-none');
            
            const modalContent = scoreModal.querySelector('div');
            modalContent.classList.remove('scale-100');
            modalContent.classList.add('scale-90');
        }
        
        // 分数动画
        function animateScore(start, end) {
            let current = start;
            const increment = end > start ? 1 : -1;
            const duration = 1000; // 动画持续时间（毫秒）
            const steps = Math.abs(end - start);
            const interval = duration / steps;
            
            const timer = setInterval(() => {
                current += increment;
                scoreDisplay.textContent = current;
                
                if (current === end) {
                    clearInterval(timer);
                }
            }, interval);
        }
        
        // 事件监听 - 触摸事件（移动设备）
        canvas.addEventListener('touchstart', (e) => {
            e.preventDefault(); // 防止默认行为（如滚动）
            const touch = e.touches[0];
            const rect = canvas.getBoundingClientRect();
            const x = touch.clientX - rect.left;
            const y = touch.clientY - rect.top;
            startDrawing(x, y);
        });
        
        canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            if (!isDrawing) return;
            const touch = e.touches[0];
            const rect = canvas.getBoundingClientRect();
            const x = touch.clientX - rect.left;
            const y = touch.clientY - rect.top;
            draw(x, y);
        });
        
        canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            endDrawing();
        });
        
        // 事件监听 - 鼠标事件（调试用）
        canvas.addEventListener('mousedown', (e) => {
            const rect = canvas.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            startDrawing(x, y);
        });
        
        canvas.addEventListener('mousemove', (e) => {
            if (!isDrawing) return;
            const rect = canvas.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            draw(x, y);
        });
        
        canvas.addEventListener('mouseup', endDrawing);
        canvas.addEventListener('mouseleave', endDrawing);
        
        // 按钮事件
        startBtn.addEventListener('click', startGame);
        resetBtn.addEventListener('click', resetGame);
        modalCloseBtn.addEventListener('click', resetGame);
        forceScoreBtn.addEventListener('click', forceCalculateScore);
        
        // 防止页面滚动干扰游戏
        document.body.addEventListener('touchmove', (e) => {
            if (isDrawing) {
                e.preventDefault();
            }
        }, { passive: false });
    </script>
</body>
</html>
